package rs.etf.kdp.client;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.List;

import javax.swing.JOptionPane;
import javax.swing.JTextArea;

import rs.etf.kdp.server.Result;

public class Receiver extends Thread {

	ObjectInputStream serverIn;
	JTextArea status;
	RequestedJobsCollection req;
	RegistrationBuffer buff;

	public Receiver(ObjectInputStream serverIn, JTextArea status, RegistrationBuffer buff) {
		this.status = status;
		this.serverIn = serverIn;
		req = ClientGUI.req;
		this.buff = buff;
	}



	public void run()
	{
		try {
			while(true)
			{
				String fromServer = null;
				try {
					fromServer = (String)serverIn.readObject();
				} catch (IOException e) {
					status.append("\nSender: Unable to recieve message in second phase ");
					return;
				} catch (ClassNotFoundException e) {
					status.append("\nSender: ClassNotFound while waiting from the other server messages(after job sent)");
					return;
				}

				if(fromServer.startsWith("status"))
				{
					String read = null;
					String[] tok = fromServer.split(" ");
					try {
						read = (String)serverIn.readObject();
					} catch (Exception e) {
						status.append("\nError while receiving status");
					} 

					if(read!=null)
					{
						req.setNewJobsStatus(Long.parseLong(tok[1]), read);
						JOptionPane.showMessageDialog(null, "Status on server for job with id " + tok[1] + " is " + read);
					}
				}
				else if (fromServer.startsWith("result"))
				{
					String[] tok = fromServer.split(" ");
					Long id = Long.parseLong(tok[1]);
					req.setNewJobsStatus(id, "DONE");
					File file = null;
					for(Sender.FileLocation f : Sender.fileLocations)
					{
						if(f.getId()==id) file = f.getFile();
					}
					FileWriter wr = null;
					try {
						wr = new FileWriter(file);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					BufferedWriter write = new BufferedWriter(wr);

					Result res = null;

					try {
						res = (Result) serverIn.readObject();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					List<String[][]> str = res.getResults();
					try {
						write.append(tok[1]);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					for(String[][] s : str)
					{
						for(int i=0; i<s.length; i++)
						{
							if(i==1)
							{
								System.out.print("SD");
							}
							try {
								write.write("\n");
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							for(int j=0; j<s[i].length; j++)
							{
								try {
									write.write(s[i][j]+ " ");
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						}
					}

					try {
						write.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} else if(fromServer.equals("old fail"))
				{
					String in = null;
					try {
						in = (String) serverIn.readObject();
					} catch(IOException io)
					{
						System.out.println("ioexception");
					}
					JOptionPane.showMessageDialog(null, in);
				} else if(fromServer.equals("jobid from server"))
				{
					String in = null;
					in = (String) serverIn.readObject();
					long id = Long.parseLong(in);
					buff.setID(id);
				} else if(fromServer.startsWith("Invalid file"))
				{
					JOptionPane.showMessageDialog(null, fromServer);
				}
			}

		} catch(Exception ie)
		{
			System.out.println("Closing receiver");
		}
	}
}
